const moment = require('moment')
const jsonwebtoken = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const send = require('../config/mailConfig')
const { JWT_SECRET } = require('../config/index')
const { checkCode } = require('../common/utils')
const { findUser, checkUsername, saveUser } = require('../controller/user')

class LoginController {
  async isUnique(ctx) {
    const { username } = ctx.request.body
    const notFindUsername = await checkUsername(username)
    if (notFindUsername) {
      ctx.body = {
        code: 200,
        data: true,
        msg: '未注册'
      }
    } else {
      ctx.body = {
        code: 401,
        data: false,
        msg: '已注册'
      }
    }
  }

  async register(ctx) {
    const { username, password, name, sid, code } = ctx.request.body
    const isPermission = await checkCode(sid, code)
    if (isPermission) {
      const notFindUsername = await checkUsername(username)
      if (notFindUsername) {
        const created = moment().format('YYYY-MM-DD HH:mm:ss')
        const res = await saveUser(username, password, name, created)
        ctx.body = {
          code: 200,
          data: {
            username: res.username,
            name: res.name
          },
          msg: '注册成功'
        }
      } else {
        ctx.body = {
          code: 401,
          msg: {
            username: ['此邮箱已经注册，可以通过邮箱找回密码']
          }
        }
      }
    } else {
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确！'
      }
    }
  }

  async forget(ctx) {
    const { username } = ctx.request.body
    try {
      const result = await send({
        code: '123',
        expire: moment().add(30, 'm').format('YYYY-MM-DD HH:mm:ss'),
        email: username,
        user: '475218106@qq.com'
      })
      ctx.body = {
        code: 200,
        data: result,
        msg: '邮件发送成功'
      }
    } catch (error) {
      console.error(error)
    }
  }

  async login(ctx) {
    const { username, password, code, sid } = ctx.request.body
    const isPermission = await checkCode(sid, code)
    // 验证图片验证码
    if (isPermission) {
      const user = await findUser(username)
      if (!user) {
        ctx.body = {
          code: 401,
          msg: '您还未注册！'
        }
        return
      }
      const checkPassword = await bcrypt.compare(password, user.password)
      if (checkPassword) {
        // 验证用户名密码
        const token = jsonwebtoken.sign({ _id: '' }, JWT_SECRET, {
          expiresIn: '1s'
        })
        const userObj = user.toJSON()
        const uselessParams = ['username', 'password', 'roles']
        uselessParams.map(item => {
          delete userObj[item]
        })
        ctx.body = {
          code: 200,
          data: userObj,
          token
        }
      } else {
        ctx.body = {
          code: 401,
          msg: '用户名密码不正确！'
        }
      }
    } else {
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确！'
      }
    }
  }
}

module.exports = new LoginController()
